/**
 * Controller层只需进行业务逻辑部分的处理
 */
const { getToken, getJWTPayload } = require("../utils/token")
const loginService = require("../service/login")
const db = require("../database/db-mysql")
const UserModel = require("../model/user");
const Crypt = require("../utils/crypt");
const Store = require("../utils/Store");
const store = new Store();

module.exports = {
    /**
     * 登录
     * @param {*} ctx 
     * @param {*} next 
     */
    login: async function (ctx, next) {
        let { username, password } = ctx.request.body;//接收前端传过来的post数据

        // 参数非空检验
        if (!username || !password) {
            ctx.body = {
                status: "-1",
                msg: "用户名或密码不能为空"
            }
            return;
        }

        let user = await loginService.getUserData(ctx, username, password);
        console.log('controller:',user)
        if (user.length === 0) {
            ctx.body = {
                status: "-1",
                msg: "该用户未注册"
            }
        } else {
            if (user.password === password) {
                let role = user.role;
                // 生成token，验证登录有效期
                let token = 'Bearer ' + getToken({ username, password, role });
                let id = user.id;
                // 存储 token
                // store.set(token, { id, token, time: Date.now() });

                ctx.body = {
                    data: { username, password, role, token },
                    token: token,
                    status: 200,
                    msg: "登录成功"
                }
            } else {
                ctx.body = {
                    status: "-1",
                    msg: "用户密码错误"
                }
            }
        }
    },
    /**
     * 退出
     */
    logout: async (ctx, next) => {
        let token = ctx.header.authorization;
        // store.destroy(token);
        ctx.body = {
            data: "",
            status: 200,
            msg: "退出成功"
        }
    },
    /**
     * 注册
     */
    register: async (ctx, next) => {
        // const UserEntity = new UserModel(ctx.request.body);
        // UserEntity.password = Crypt.encrypt(UserEntity.password);
        let { username, password } = ctx.request.body;
        let encryptPass = Crypt.encrypt(password)
        let user = await loginService.register(ctx, { username: username, password: password })
        ctx.body = {
            status: 200,
            msg: "success"
        }
    },
    getMenu: async (ctx, next) => {
        // console.log('ctx:', ctx)
        // 前端访问时会附带token在请求头
        let payload = getJWTPayload(ctx.headers.authorization)
        // console.log(payload)
        // console.log(ctx.request.body)
        let { role } = ctx.request.body;
        // let menuList = await db.query("select * from role_menu where role_id = ?", [role]);
        let menuList = await loginService.getMenu(role);
        let allMenu = await processArray("-1", function (item, children) {
            let filterChildren = [];
            for (var i = 0; i < children.length; i++) {
                let child = children[i]
                let isExist = menuList.find(item => {
                    return item.menu_id === child.id
                });
                if (isExist) {
                    filterChildren.push(child)
                }
            }
            item.children = filterChildren;
        });

        // let tempMenu = [];
        // for (var i = 0; i < menuList.length; i++) {
        //     let { menu_id } = menuList[i];
        //     let menuObj = await db.query("select * from menu where id = ?", [menu_id]);
        //     tempMenu.push(menuObj[0])
        // }
        ctx.body = {
            status: 200,
            allMenu: allMenu,
            data: menuList
        }
    }
}

async function processArray(parent_id, callback) {
    let menuAry = await db.query("select * from menu where parent_id = ?", [parent_id])
    if (menuAry.length > 0) {
        for (var i = 0; i < menuAry.length; i++) {
            let item = menuAry[i];
            let children = await processArray(item.id, callback);
            callback(item, children);
        }
    }
    return menuAry;
}